#include<iostream>
#include<string>
#include<cstdio>
#include<mysql.h>

const std::string host = "127.0.0.1";
const std::string user = "hjh";
const std::string password = "hu20050610";
const std::string db = "2025_06_29"; // 我们今天用的还是昨天的数据库
unsigned int port = 3306;

int main()
{
    MYSQL * sql = nullptr;
    sql = mysql_init(sql);
    if(sql == nullptr)
    {
        std::cerr << "the init of MYSQL failed" << std::endl;
        return 1;
    }

    sql = mysql_real_connect(sql,host.c_str(),user.c_str(),password.c_str(),db.c_str(),port,nullptr,0);
    if(sql == nullptr)
    {
        std::cerr << "the connect of MYSQL failed" << std::endl;
        return 1;
    }

    mysql_set_character_set(sql,"utf8");

    //const std::string task="insert into account (name,salary)values('孙权',8500.00)"; 
    const std::string task="select * from account"; 
    int n = mysql_query(sql,task.c_str());

    if(n != 0)
        std::cerr << "warning, the sql of" << task << "execute failed" << std::endl;

    //1.0 从MYSQL中获取结果集
    MYSQL_RES* results = mysql_store_result(sql);

    //1.1 获取行和列
    int line = mysql_num_rows(results);
    unsigned int row = mysql_num_fields(results);
    //1.2 获取列名
    MYSQL_FIELD * column = mysql_fetch_fields(results);
    //2.0 打印数据库名和表名
    std::cout << "database :" << column[0].db << " " 
    << "table :" << column[0].table << " " 
    << "size :"  <<  line << " " << row << std::endl;  

    //2.1 打印列名
    for(int i = 0 ; i < row ; i++)
        std::cout << column[i].name<< " "; 

    std::cout << std::endl;

    //2.2 打印表的内容
    for(int i = 0 ; i < line ; i++)
    {
        MYSQL_ROW line = mysql_fetch_row(results);
        for(int j = 0 ; j < row ; j++)
        {
            std::cout << line[j] << " ";
        }
        std::cout << std::endl;
    }

    mysql_free_result(results);

    mysql_close(sql);
    return 0;
}